package com.crazymakercircle.objectpool;

import com.crazymakercircle.util.Print;
import lombok.Getter;
import org.apache.commons.pool2.KeyedPooledObjectFactory;
import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig;

public class CacheObjectPool {
    @Getter
    private final GenericKeyedObjectPool<CacheKey, CacheObject> pool;
    public CacheObjectPool() {
        GenericKeyedObjectPoolConfig<CacheObject> config = new GenericKeyedObjectPoolConfig<>();
        config.setMaxTotal(10);        // 最大资源数


        config.setMaxTotalPerKey(10);  // 每个 key 对应的最大资源数

        config.setMaxIdlePerKey(10);   // 最大 key 数量

        config.setBlockWhenExhausted(true);     // 没有可用资源时是否要等待

        config.setTestOnCreate(false);   // 创建新资源对象后是否立即校验是否可用

        config.setTestOnBorrow(true); // 借用资源对象前是否校验是否可用
        KeyedPooledObjectFactory<CacheKey, CacheObject> factory = new MyPooledObjectFactory();
        this.pool = new GenericKeyedObjectPool<>(factory, config);
    }

    public static void main(String[] args) throws Exception {
        CacheObjectPool cacheObjectPool = new CacheObjectPool();
        GenericKeyedObjectPool<CacheKey, CacheObject> pool = cacheObjectPool.getPool();
        CacheKey key = new CacheKey("技术自由圈");
        for (int i = 0; i < 3; i++) {
            Print.tcfo(i+" ---------------------");
            CacheObject cacheObject = pool.borrowObject(key);
            cacheObject.doing();
            pool.returnObject(key, cacheObject);
        }
    }
}
